package com.tdcy.sys.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import com.tdcy.framework.util.ContextUtils;
import com.tdcy.framework.util.DateUtils;

/**
 * 
 * @ClassName: MemcachedUtils
 * @Description: Memcached
 * 
 */
public class EhcacheUtils {
	public static Element getCache(String cacheName, String cacheKey) {
		CacheManager manager = ContextUtils.getApplicationContext().getBean(
				CacheManager.class);
		Element el = null;
		Cache cache = manager.getCache(cacheName);

		if (cache.isKeyInCache(cacheKey)) {
			el = cache.get(cacheKey);
			return el;
		}

		return null;
	}

	public static void setCache(String cacheName, String cacheKey, Object obj) {
		CacheManager manager = ContextUtils.getApplicationContext().getBean(
				CacheManager.class);
		Cache cache = manager.getCache(cacheName);
		cache.put(new Element(cacheKey, obj));
	}

	public static void removeCache(String cacheName, String cacheKey) {
		CacheManager manager = ContextUtils.getApplicationContext().getBean(
				CacheManager.class);
		Cache cache = manager.getCache(cacheName);
		if (cache.isKeyInCache(cacheKey)) {
			cache.remove(cacheKey);
		}
	}

	public static List<Map<String, String>> getCacheList(String cacheKey) {
		List<Map<String, String>> retList = new ArrayList<Map<String, String>>();

		CacheManager manager = ContextUtils.getApplicationContext().getBean(
				CacheManager.class);
		String[] names = manager.getCacheNames();
		for (int i = 0; i < names.length; i++) {
			Cache cache = manager.getCache(names[i]);

			Collection<String> cs = cache.getKeys();
			for (Iterator<String> it = cs.iterator(); it.hasNext();) {
				String n = it.next();
				Element el = cache.get(n);
				Map<String, String> m = new HashMap<String, String>();
				m.put("cname", names[i]);
				m.put("ckey", n);
				Object v = el.getValue();
				if(v!=null){
					m.put("cvalue", v.toString());
				}

				m.put("remark",
						DateUtils.dateToString(
								new Date(el.getLastUpdateTime()),
								"yyyy-MM-dd hh:mm:ss"));
				retList.add(m);

			}
		}

		return retList;
	}
}